import { useState, useEffect, useCallback, useRef } from 'react';
import type { Position, Tab } from '../types';
import { updateTab } from '../api';

const useDragView = (
    ref: React.RefObject<HTMLDivElement | null>,
    tab: Tab,
) => {
    const init = useRef<boolean>(false);
    const [offset, setOffset] = useState<Position>({
        x: tab.offsetX,
        y: tab.offsetY,
    });
    const [scale, setScale] = useState<number>(tab.scale); // 视图缩放
    const timerRef = useRef<number>(null)
    const [isSpacePressed, setIsSpacePressed] = useState<boolean>(false); // 是否按住空格

    const [isDragging, setIsDragging] = useState<boolean>(false);   // 视图是否拖拽
    const [dragStart, setDragStart] = useState<Position>({ x: 0, y: 0 }); // 视图开始拖拽的位置

    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.code === 'Space') {
                e.preventDefault();
                setIsSpacePressed(true);
            }
        };

        const handleKeyUp = (e: KeyboardEvent) => {
            if (e.code === 'Space') {
                setIsSpacePressed(false);
                if (isDragging) {
                    setIsDragging(false);
                }
            }
        };

        document.addEventListener('keydown', handleKeyDown);
        document.addEventListener('keyup', handleKeyUp);

        return () => {
            document.removeEventListener('keydown', handleKeyDown);
            document.removeEventListener('keyup', handleKeyUp);
        };
    }, [isDragging]);


    const startDragView = useCallback(
        (e: React.MouseEvent) => {
            if (isSpacePressed && e.button === 0) {
                setIsDragging(true);
                setDragStart({
                    x: e.clientX - offset.x,
                    y: e.clientY - offset.y,
                });
            }
        },
        [isSpacePressed, offset.x, offset.y]
    );

    const endDragView = () => {
        setIsDragging(false);
    }

    useEffect(() => {
        if (!init.current) {
            init.current = true;
            return;
        }

        if (timerRef.current) {
            clearTimeout(timerRef.current)
        }
        timerRef.current = window.setTimeout(() => {
            updateTab(tab?.id, { offsetX: offset.x, offsetY: offset.y, scale });
        }, 500)

        return () => {
            if (timerRef.current) {
                clearTimeout(timerRef.current)
            }
        }
    }, [offset, scale])

    // 缩放视图
    const zoomView = useCallback(
        (e: React.WheelEvent) => {
            const zoomIntensity = 0.1;
            const oldScale = scale;
            const newScale = e.deltaY < 0 ? oldScale * (1 + zoomIntensity) : oldScale * (1 - zoomIntensity);

            // 限制缩放范围
            const clampedScale = Math.max(0.3, Math.min(2, newScale));

            if (ref.current) {
                const rect = ref.current.getBoundingClientRect();
                // 计算鼠标相对于容器的位置
                const mouseX = e.clientX - rect.left;
                const mouseY = e.clientY - rect.top;

                // 计算鼠标在缩放前的画布坐标
                const canvasX = (mouseX - offset.x) / oldScale;
                const canvasY = (mouseY - offset.y) / oldScale;

                // 计算缩放后的新偏移量，使鼠标点保持在同一位置
                const newOffsetX = mouseX - canvasX * clampedScale;
                const newOffsetY = mouseY - canvasY * clampedScale;

                setScale(clampedScale);
                setOffset({ x: newOffsetX, y: newOffsetY });
            }
        },
        [scale, offset]
    );

    const updateOffset = (e: React.MouseEvent) => {
        setOffset({
            x: e.clientX - dragStart.x,
            y: e.clientY - dragStart.y,
        });
    }


    return { offset, scale, isSpacePressed, isDragging, updateOffset, setOffset, startDragView, endDragView, zoomView }
}

export default useDragView